﻿using Raffles.OA.Utility;
using Raffles.OA.Data;
using Mapster;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.UI.WebControls;

namespace Raffles.OA.WebApp.Areas.Manage.Controllers
{ 
    public class DepartmentController : BaseController<Department>
    {
        /// <summary>
        /// 获取部门列表树形表格
        /// </summary> 
        /// <returns></returns>
        public JsonResult GetTreeData()
        {
            try
            {
                var data = _dbContext.Queryable<Department>()
                                     .Where(x => !x.DeletedMark)
                                     .OrderBy(x => x.DisplayOrder)
                                     .Select(x => new DepartTreeVo
                                     {
                                         id = x.Id,
                                         pId = x.ParentId, 
                                         Name = x.Name, 
                                         DisplayOrder = x.DisplayOrder
                                     }).ToList();

                return Json(DataResult<List<DepartTreeVo>>.Success(data, "加载成功"), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(DataResult.Error($"部门树加载错误,错误原因:{ex.Message}"), JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult Form(int? id)
        {
            Department department = new Department(); 
            if (id != null)
            {
                department = _dbContext.Queryable<Department>().InSingle(id); 
            } 
            return View(department);
        }

        /// <summary>
        /// 部门保存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveForm(DepartDto departDto)
        {
            try
            {
                if (departDto.Id == null)
                {
                    Department department = new Department();
                    departDto.Adapt(department);
                    department.ParentId = departDto.TreeId;
                    department.CreatedBy = OperatorProvider.Provider.GetCurrent().Id;
                    _dbContext.Insertable<Department>(department).ExecuteCommand();
                    return Json(DataResult.Success("部门新增成功"));
                }
                else
                {
                    Department department = _dbContext.Queryable<Department>().InSingle(departDto.Id);
                    departDto.Adapt(department);
                    department.ParentId = departDto.TreeId;
                    department.UpdatedOn = DateTime.Now;
                    department.UpdatedBy = OperatorProvider.Provider.GetCurrent().Id;
                    _dbContext.Updateable<Department>(department).ExecuteCommand();
                    return Json(DataResult.Success("部门编辑成功"));
                } 
            }
            catch (Exception ex)
            {
                return Json(DataResult.Error($"保存失败,失败原因:{ex.Message}"));
            }
        }

        /// <summary>
        /// 部门删除
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DeleteData(int id)
        {
            if (_dbContext.Queryable<Department>().Any(x =>!x.DeletedMark&&x.ParentId == id))
            {
                return Json(DataResult.Error("该部门下存在子部门,不允许删除"));
            }
            if (_dbContext.Queryable<User>().Any(x => !x.DeletedMark && x.DepartmentId == id))
            {
                return Json(DataResult.Error("该部门下存在员工,不允许删除"));
            }
            Department department = _dbContext.Queryable<Department>().InSingle(id);
            department.DeletedMark = true;
            department.UpdatedOn = DateTime.Now;
            department.UpdatedBy = OperatorProvider.Provider.GetCurrent().Id;
            _dbContext.Updateable<Department>(department).ExecuteCommand();
            return Json(DataResult.Success("删除成功"));
        }

        /// <summary>
        /// 获取部门树
        /// </summary> 
        /// <returns></returns>
        public JsonResult GetDepartTreeSelect()
        {
            List<TreeVo> treeDtos = new List<TreeVo>();
            try
            {
                treeDtos = _dbContext.Queryable<Department>().Where(x => !x.DeletedMark && x.EnabledMark)
                                       .OrderBy(x => x.DisplayOrder)
                                       .Select(x => new TreeVo { id = x.Id, pId = x.ParentId, name = x.Name })
                                       .ToList();

                return Json(DataResult<List<TreeVo>>.Success(treeDtos, "加载成功"), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(DataResult.Error($"下拉树加载错误,错误原因:{ex.Message}"), JsonRequestBehavior.AllowGet);
            }
        }

        public ActionResult GetDepartTreeJson()
        {
            List<TreeVo> treeDtos = new List<TreeVo>();
            treeDtos = _dbContext.Queryable<Department>().Where(x => !x.DeletedMark && x.EnabledMark)
                                      .OrderBy(x => x.DisplayOrder)
                                      .Select(x => new TreeVo { id = x.Id, pId = x.ParentId, name = x.Name })
                                      .ToList();
            return Content(treeDtos.ToJson());
        }
    }
}